<?php
header('Pragma: public');
$exp = 60*60*24*365;
header('Cache-Control: max-age=' . $exp);
header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time()+$exp) . '');
define('SERIES_CALENDAR', true);
setLocale(LC_ALL, 'hu_HU.utf-8', 'Hungarian_Hungary');
require "includes/config.php";
require "includes/autoloader.php";
require "includes/functions.php";

$db = new sql('localhost', DB_USER, DB_PASS, DB_NAME);

$settings = new settings();
$user = new users();

$m = request_var('mode');
$e = request_var('ext','json');

$result = '';

switch($m){

	case 'servertime':
		$tv = new TheTvDB();
		$result = array('Time' => (int) $tv->getPreviousTime());
	break;

	case 'searchseries':
		$tv = new TheTvDB();
		$result = $tv->searchSeries(request_var('value2', ''), request_var('value1', 1, 'int'));
	break;

	case 'seriesbyid':
		$tv = new TheTvDB();
		$result = $tv->getSeria(request_var('value1', 0, 'int'), request_var('value2', 0, 'int'));
	break;

	case 'seriesbyname':
		$tv = new TheTvDB();
		$result = $tv->getSeria(request_var('value1', ''), request_var('value2', 0,'int'), true);
	break;

	case 'updateseriesbyid':
		$tv = new TheTvDB();
		$result = $tv->updateSeriesById(request_var('value1', 0, 'int'));

	break;

	case 'continuing':
		$tv = new TheTvDB();
		$result = $tv->getContinuingSeries(true);
	break;

	case 'userstatus':
		$result = $user->data;
	break;

	case 'userlogout':
		$user->logOut();
		$result = $user->data;
	break;

	case 'userlogin':
		$data = request_var('login', false);
		if($data){
			if($user->login($data,@(bool)$data['permanent'])){
				$result = 'OK';
			}
			else {
				$result = 'ERR';
			}
		}
	break;

	case 'userregister':
		$data = request_var('register', false);
		if($data){
			if($user->register($data))
				$result = 'OK';
			else
				$result = 'ERR';
		}
	break;

	case 'usersettings':
		$data = request_var('settings', false);
		if($data){
			if($user->loginModify($data))
				$result = 'OK';
			else
				$result = 'ERR';
		}
	break;

	case 'userpreferences':
		if(($data = request_var('user_settings', false, 'array')) && $user->isLoggedIn())
		{
			if(is_array($data) && count($data))
			{
				foreach($data as $key => $date)
				{
					$user->$key = $date;
				}
				$result = 'OK';
			}
			else
			{
				$result = 'ERR';
			}
		}
		else {
			$result = 'ERR';
		}
	break;

	case 'userseries':
		$v1 = request_var('value1', false, array('add', 'remove'));
		$v2 = request_var('value2', false, 'int');

		if($v1 and $v2 and $user->isLoggedin()){
			$result = $user->setSerie($v2);
		}
	break;

	case 'calendar':
		$year = (int)request_var('value1',strftime('%Y'));
		$month = (int)request_var('value2',strftime('%m'));
		$showAll = (bool)request_var('value3', false);

		$tv = new TheTvDB;
		$matches = $tv->getCalendar($year, $month, $showAll);

		$result = array('date' => "{$year}-".sprintf('%02d',$month)."-01",'caldays' => $matches);

	break;

	case 'update':
		$tv = new DBUpdater;
	break;

	case 'tops':
		$tv = new TheTvDB;
		$result = $tv->mostPopularSeries();
	break;

	case 'rank':
		$id = request_var('value1', false, 'int');
		$rank = request_var('value2', false, 'numeric');
		if(!$id or !$rank){
			$result = false;
		}
		else {
			$r = new Rank;
			$r->$id = $rank;
			$result = $r->result;
		}
	break;

	case 'addreview':

		$epid = request_var('episodeid',false,'int');
		$text = request_var('review',false);
		if($epid and $text){
			$rv = new reviews($epid);
			if($rv->addReview($text))
				$result = 'OK';
			else
				$result = 'ERR';
		}
		else
			$result = 'ERR';
	break;

	case 'getreviews':
		$epid = request_var('value1', false, 'int');
		$page = request_var('value2', 1, 'int');

		if($epid){
			$rv = new reviews($epid);

			$result = array('pages' => $rv->pageCount(),'reviews' => $rv->getReviews($page));
		}
	break;

	// case "fb_register":
	// 	if($user->isLoggedIn()){
	// 		$eh = new emailhash($user->data['user_email']);
	// 		//$result = $eh->getHash();
	// 		$result = $user->fb->api(array(
	// 			"method" => "connect.registerUsers",
	// 			"accounts" => array(
	// 				'email_hash' => $eh->getHash(),
	// 				'account_id' => (int)$user->data['id']
	// 			)
	// 		));
	// 	}
	// break;
	//
	// case "fb_unregister":
	// 	if($user->isLoggedIn()){
	// 		$eh = new emailhash($user->data['user_email']);
	// 		$fb = new Facebook(FB_API_KEY, FB_SECRET_KEY);
	// 		$result = $fb->api_client->connect_unregisterUsers(array(
	// 				'email_hash' => $eh->getHash()
	// 		));
	// 	}
	// break;

	case 'fb_auth':
		 // if($_POST)
		 // 	file_put_contents('auth.json', json_encode($_POST));
		 // if($user)
		 // 	file_put_contents('user.json', json_encode($user));

		$fb_sig_linked_account_ids = request_var('fb_sig_linked_account_ids');
		list($id) = ($fb_sig_linked_account_ids) ? json_decode($fb_sig_linked_account_ids, true) : array(false);

		if(request_var('fb_sig_added') and request_var('fb_sig_authorize') == 1)
		{
			$result = $user->fb_addUser(request_var('fb_sig_user'), $id);
		}
		elseif(request_var('fb_sig_uninstall') and request_var('fb_sig_uninstall') == 1){
			$result = $user->fb_removeUser(request_var('fb_sig_user'), $id);
		}
	break;

	// case "fb_test":
	// 	$fql = "SELECT name, first_name, last_name FROM user WHERE uid = '". $user->fb->getUser() . "'";
	// 	list($result) = $user->fb->api(array(
	// 		"method" => "fql.query",
	// 		"query" => $fql
	// 	));
	// 	$result = false;
	// break;

	case 'torrentsearch':
		$t = new TorrentSearch(request_var('value1', false, 'string'), request_var('value2', false, 'string'),request_var('value3', false, 'string'));
		$result = $t->getResults();
	break;

	case 'lostpwd':
		if($user->lostPassword(request_var('lostpwd', false, 'string')))
			$result = "OK";
		else
			$result = "ERR";
	break;

	case 'sitemap':
		@ini_set("memory_limit", '64M');
		header("Content-type: text/xml; charset=utf-8");
		$result = array();
		echo '<?xml version=\'1.0\' encoding=\'UTF-8\'?>
		<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
			xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
			xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
					    http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">';

		echo "<url>";
		echo "<loc>http://{$settings->data['host']}/</loc>";
		echo "<lastmod>" . strftime("%F") . "</lastmod>";
		echo "<changefreq>daily</changefreq>";
		echo "<priority>0.9</priority>";
		echo "</url>";

		$sql = "SELECT e.`seasonnumber`, e.`episodenumber`, e.`episodename`, e.`last_updated`, s.`seriesname` FROM `" . EPISODES_TABLE . "` e LEFT JOIN `" . SERIES_TABLE . "` s on s.id = e.seriesid WHERE e.`firstaired` != '0000-00-00' ORDER BY s.id, e.`seasonnumber`, e.`episodenumber`";// and s.`status` = 'Continuing'
		if($db->query($sql) && $db->affected_rows())
		{
			$rows = $db->fetch_assoc();
			foreach($rows as $row)
			{

				echo "<url>";
				echo "<loc>http://{$settings->data['host']}/e/". rawurlencode($row["seriesname"]) . "/{$row["seasonnumber"]}x".  sprintf("%02d", $row["episodenumber"]) . "/". rawurlencode($row["episodename"]) ."</loc>";
				echo "<lastmod>" . strftime("%F", strtotime($row["last_updated"])) . "</lastmod>";
				echo "<changefreq>weekly</changefreq>";
				echo "<priority>0.8</priority>";
				echo "</url>";
			}
		}
		echo "</urlset>";
		exit(0);
	break;

	case 'sendFeedback':
		if($user->isLoggedIn() && ($content = request_var('content', false, 'string')) && mb_strlen($content) > 10)
		{
			$text = "Feladó: {$user->data['user_email']}<br><br>";
			$text .= nl2br($content);
			$text .= "<br><br>{$_SERVER['HTTP_USER_AGENT']}";

			$headers = "From: Mit nézel? <no-reply@mitnezel.net>\r\n";
			$headers .= "Reply-To: {$user->data['user_email']}\r\n";
			$headers .= 'MIME-Version: 1.0' . "\r\n";
			$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";

			if(mail(SITE_MAIL, 'Mit nézel? ~ Visszajelzés', $text, $headers))
				exit(0);
		}

		header("HTTP/1.0 400 Bad Request");
    header("Status: 400 Bad Request");
		$_SERVER['REDIRECT_STATUS'] = 400;
		exit(0);
	break;

}

if(!is_array($result)){
	$result = array($result);
}

switch($e){
	case 'json':
		header('Content-type: text/json; charset=utf-8');
		echo json_encode($result);
	break;

	case 'php':
		header('Content-type: text/text; charset=utf-8');
		_pr($result);
	break;

	case 'html':
		header('Content-type: text/html; charset=utf-8');
		__pr($result);
	break;
}
?>